import Base from '../../base'
import view from '../../views/game/player.json'

export default class Player extends Base {

	constructor(scene) {
		super(scene,view)
        this.player = {
			name: '凯哥',
			sex: 1,
			x: 200,
			y: 100,
			dress: 0,
			status: 1, //状态: 0站 1走 2跑 3砍 4挖矿 5跳斩 6魔法 7挖地(共16格) 8受击 9死亡
			dir: 0, //方向: 0上 1右上 2右 3右下 4下 5左下 6左 7左上
		}
		this.statusFrameNum = [4, 6, 6, 6, 6, 8, 6, 2, 3, 4];
		this.statusFrameRate = [5, 8, 5, 6, 6, 8, 6, 2, 3, 4];
	}

	create() {
		this.scene.mapModule.loadMap()
		let body = 'body'+ this.player.sex + this.player.dress
		this.view['playerName'].text = this.player.name
		this.view[body].visible = true
		this.view[body].anims.play(this.view[body].conf.url)
	}

	upBodyAnims(status = 0) {
		let repeat = status > 0 ? 0 : -1
		this.player.status = status
		let body = 'body'+ this.player.sex + this.player.dress
		let start = this.player.status * 8 * 8 + this.player.dir * 8
		this.view[body].conf.start = start
		this.view[body].conf.end = start + this.statusFrameNum[this.player.status] - 1
		this.view[body].anims.play({key: this.view[body].conf.url, repeat: repeat, frameRate: this.statusFrameRate[this.player.status]})
	}

	move(moveTo, status = 1) {
		let body = 'body'+ this.player.sex + this.player.dress
		let moveDir = this.upDir(body, moveTo.x, moveTo.y)
		this.upBodyAnims(status)
		this.view[body].once(Phaser.Animations.Events.ANIMATION_COMPLETE, () => {
			this.upBodyAnims(0)
		})
		return moveDir
	}

	upDir(body, x, y) {
		let xyDir = {x:0, y:0}
		let rads = Phaser.Math.Angle.BetweenY(this.view[body].x, this.view[body].y, x, y)
		if(rads < -2.7475 || rads > 2.7475) {
			this.player.dir = 0
			xyDir.y = -1
		} else if(rads < 2.7475 && rads > 1.9625) {
			this.player.dir = 1
			xyDir.x = 1
			xyDir.y = -1
		} else if(rads < 1.9625 && rads > 1.1775) {
			this.player.dir = 2
			xyDir.x = 1
		} else if(rads < 1.1175 && rads > 0.3925) {
			this.player.dir = 3
			xyDir.x = 1
			xyDir.y = 1
		} else if(rads < 0.3925 && rads > -0.3925) {
			this.player.dir = 4
			xyDir.y = 1
		} else if(rads < -0.3925 && rads > -1.1775) {
			this.player.dir = 5
			xyDir.x = -1
			xyDir.y = 1
		} else if(rads < -1.1775 && rads > -1.9625) {
			this.player.dir = 6
			xyDir.x = -1
		} else if(rads < -1.9625 && rads > -2.7475) {
			this.player.dir = 7
			xyDir.x = -1
			xyDir.y = -1
		}
		return xyDir
	}
}